package com.example.fengyungo.controller.user.user;

import com.example.fengyungo.constant.MsgConstant;
import com.example.fengyungo.domain.pojo.Driver;
import com.example.fengyungo.domain.pojo.User;
import com.example.fengyungo.result.Result;
import com.example.fengyungo.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/user/user")
public class UserUserController {

    @Autowired
    private UserService userService;

    @Autowired
    private DriverService driverService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 清理缓存数据
     *
     * @param pattern String
     */
    private void cleanCache(String pattern) {
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }

    /**
     * 登录，返回对应用户数据
     *
     * @param username 用户名
     * @param password 密码
     * @return 返回对应用户数据
     */
    @GetMapping("/login/{username}/{password}")
    public Result login(@PathVariable String username, @PathVariable String password) {
        List<User> users = userService.getUserByUsernameAndPassword(username, password);
        return Result.success(users);
        // return loginService.login(username, password);
    }

    /**
     * 注册
     *
     * @param user 用户
     * @return 注册是否成功
     */
    @PostMapping("/register")
    public Result<Boolean> addUser(@RequestBody User user) {
        Boolean res = userService.addUser(user);
        // 清除缓存
        cleanCache("fengyungouser*");
        return Result.success(res);
    }

    /**
     * 判断用户名是否被使用
     *
     * @param username 用户名
     * @return Result
     */
    @GetMapping("/judgeUsername/{username}")
    @Cacheable(value = "user", key = "'judgeUsername'+#username")
    public Result<Boolean> judgeUsername(@PathVariable String username) {
        List<User> userByUsername = userService.getUserByUsername(username);
        if (userByUsername.size() > 0) {
            return Result.error(MsgConstant.USERNAME_EXIST);
        }
        Driver driver = driverService.getDriverByUsername(username);
        if (driver != null) {
            return Result.error(MsgConstant.USERNAME_EXIST);
        }
        return Result.success(true);
    }

    /**
     * 判断邮箱是否已经注册
     *
     * @param mail 邮箱
     * @return Result
     */
    @GetMapping("/judgeMail/{mail}")
    @Cacheable(value = "user", key = "'judgeMail'+#mail")
    public Result<Boolean> judgeMail(@PathVariable String mail) {
        List<User> userByMail = userService.getUserByMail(mail);
        if (userByMail.size() > 0) {
            return Result.error("该邮箱已被注册");
        }
        return Result.success(true);
    }

    /**
     * 修改用户昵称
     *
     * @param nickname 昵称
     * @param id       用户id
     * @return Result<Boolean>
     */
    @PutMapping("/updateNicknameById/{id}/{nickname}")
    public Result<Boolean> updateNicknameById(@PathVariable String nickname, @PathVariable String id) {
        Integer update = userService.updateNicknameById(nickname, id);
        // 清除缓存
        cleanCache("fengyungouser*");
        if (update > 0) {
            return Result.success();
        } else {
            return Result.error(MsgConstant.USER_INFO_UPDATE_FAIL);
        }
    }

    /**
     * 修改用户性别
     *
     * @param sex 性别
     * @param id  用户id
     * @return Result<Boolean>
     */
    @PutMapping("/updateSexById/{id}/{sex}")
    public Result<Boolean> updateSexById(@PathVariable String sex, @PathVariable String id) {
        Integer update = userService.updateSexById(sex, id);
        // 清除缓存
        cleanCache("fengyungouser*");
        if (update > 0) {
            return Result.success();
        } else {
            return Result.error(MsgConstant.USER_INFO_UPDATE_FAIL);
        }
    }

    /**
     * 修改用户电话
     *
     * @param phone 电话
     * @param id    用户id
     * @return Result<Boolean>
     */
    @PutMapping("/updatePhoneById/{id}/{phone}")
    public Result<Boolean> updatePhoneById(@PathVariable String phone, @PathVariable String id) {
        Integer update = userService.updatePhoneById(phone, id);
        // 清除缓存
        cleanCache("fengyungouser*");
        if (update > 0) {
            return Result.success();
        } else {
            return Result.error(MsgConstant.USER_INFO_UPDATE_FAIL);
        }
    }

    /**
     * 修改用户信息，根据id
     *
     * @param user Driver
     * @return Result
     */
    @PutMapping("/updateUser")
    public Result<Boolean> updateUser(@RequestBody User user) {
        Integer update = userService.updateUserById(user);
        // 清除缓存
        cleanCache("fengyungouser*");
        if (update > 0) {
            return Result.success();
        } else {
            return Result.error(MsgConstant.USER_INFO_UPDATE_FAIL);
        }
    }

    /**
     * 修改密码
     *
     * @param username    用户名
     * @param oldPassword 原密码
     * @param newPassword 新密码
     * @return Result
     */
    @PutMapping("/changePassword/{username}/{oldPassword}/{newPassword}")
    public Result changePassword(@PathVariable String username,
                                 @PathVariable String oldPassword, @PathVariable String newPassword) {
        String password = userService.getOldPassword(username);
        if (!password.equals(oldPassword)) {
            // 如果原密码不正确
            return Result.error(MsgConstant.OLD_PASSWORD_ERROR);
        }
        if (userService.updatePassword(username, newPassword) > 0) {
            return Result.success();
        } else {
            return Result.error(MsgConstant.UPDATE_FAIL);
        }
    }

}
